package com.anjbo.common;

import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    private Boolean https;
    private File keyStore;
    private Charset charset = Consts.UTF_8;
    private CloseableHttpClient httpClient;
    private static int CONNTIMEOUT = 10000;
    public HttpUtil() {
        this(false);
    }

    public HttpUtil(Boolean https) {
        this(https, null, null);
    }

    public HttpUtil(Boolean https, File keyStore, String password) {
        try {
            if (https) {
                if (keyStore == null || password == null) {//信任所有
                    TrustManager[] trustAllCerts = new TrustManager[]{
                            new X509TrustManager() {
                                public X509Certificate[] getAcceptedIssuers() {
                                    return null;
                                }

                                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                                    // don't check
                                }

                                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                                    // don't check
                                }
                            }
                    };
                    SSLContext ctx = SSLContext.getInstance("TLS");
                    ctx.init(null, trustAllCerts, null);
                    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
                    httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
                } else {
                    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    FileInputStream in = new FileInputStream(keyStore);
                    ks.load(in, password.toCharArray());
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init(ks);
                    SSLContext ctx = SSLContext.getInstance("TLS");
                    ctx.init(null, tmf.getTrustManagers(), null);
                    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
                    httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
                }
            } else {
                httpClient = HttpClients.createDefault();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public String get(String url, Map<String, String> params) {
        HttpGet httpGet=null;
        CloseableHttpResponse response=null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (params != null && params.size() > 0) {
                List<NameValuePair> qparams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                builder.setParameters(qparams);
            }
            httpGet = new HttpGet(builder.build());
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(httpGet!=null){
                httpGet.releaseConnection();
            }
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public String post(String url, Map<String, String> params) {
        HttpPost httpPost=null;
        CloseableHttpResponse response=null;
        try {
            httpPost = new HttpPost(url);
            if (params != null && params.size() > 0) {
                List<NameValuePair> qparams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(qparams, charset));
            }
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpPost!=null){
                httpPost.releaseConnection();
            }
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public String postJson(String url, Object jsonParam) {
        HttpPost httpPost=null;
        CloseableHttpResponse response=null;
        try {
            httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(new Gson().toJson(jsonParam), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpPost!=null){
                httpPost.releaseConnection();
            }
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public String postFiles(String url, Map<String, String> params, Map<String, File> files) {
        HttpPost httpPost=null;
        CloseableHttpResponse response=null;
        try {
            httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if(params!=null){
                for(Map.Entry<String, String> param:params.entrySet()){
                    builder.addPart(param.getKey(),new StringBody(param.getValue(), ContentType.TEXT_PLAIN));
                }
            }
            if(files!=null){
                for(Map.Entry<String, File> file:files.entrySet()){
                    builder.addPart(file.getKey(),new FileBody(file.getValue()));
                }
            }
            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpPost!=null){
                httpPost.releaseConnection();
            }
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static String jsonPost(String strURL, Object obj) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setConnectTimeout(CONNTIMEOUT);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            //对象转json字符串
            String params= JSONObject.fromObject(obj).toString();
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            InputStream is = connection.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is,"utf-8"));
            String line=null;
            StringBuilder sb=new StringBuilder();
            while((line=br.readLine())!=null){
                sb.append(line);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }
}